﻿using System;

namespace Cubicle.Core.Processors
{
    public class TryCatchProcessor<T> : ProcessorQueue<T> where T : class
    {

        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public override T ProcessQueue(T input)
        {
            T result = null;
            try
            {
                input = PreProcess(input);
                result = base.ProcessQueue(input);
                result = PostProcess(result);
                return result;
            }
            catch (Exception ex)
            {
                return OnException(ex, result);
            }
        }

        public virtual T PreProcess(T input)
        {
            return input;
        }

        public virtual T PostProcess(T output)
        {
            return output;
        }

        public virtual T OnException(Exception ex, T input)
        {
            while (ex != null)
            {
                _logger.ErrorException("Inner queue threw an exception!", ex);
                ex = ex.InnerException;
            }
            return input;
        }

    }

}